<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<!-- 客服端全局消息通知组件 -->
<div th:fragment="notification">
    <!-- 用户消息通知 -->
    <div id="customerServiceNotification" class="position-fixed" style="bottom: 20px; right: 20px; z-index: 9999; display: none;">
        <div class="card shadow-lg border-0" style="width: 350px; border-radius: 15px; overflow: hidden;">
            <div class="card-header bg-success text-white d-flex justify-content-between align-items-center" style="border-radius: 15px 15px 0 0;">
                <div class="d-flex align-items-center">
                    <i class="bi bi-person me-2"></i>
                    <strong>用户消息</strong>
                </div>
                <button type="button" class="btn-close btn-close-white" onclick="closeServiceNotification()"></button>
            </div>
            <div class="card-body p-3">
                <div class="d-flex align-items-start">
                    <div class="flex-shrink-0 me-3">
                        <div class="bg-success text-white rounded-circle d-flex align-items-center justify-content-center" 
                             style="width: 40px; height: 40px;">
                            <i class="bi bi-person"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1">
                        <h6 class="mb-1" id="serviceNotificationTitle">用户发送了新消息</h6>
                        <p class="mb-2 text-muted small" id="serviceNotificationContent">您有新的用户咨询，请及时回复</p>
                        <div class="d-flex gap-2">
                            <button class="btn btn-success btn-sm" onclick="goToConversations()">
                                <i class="bi bi-chat-left-text"></i> 查看对话
                            </button>
                            <button class="btn btn-outline-secondary btn-sm" onclick="closeServiceNotification()">
                                稍后处理
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 客服端全局消息检测脚本 -->
    <script>
        let serviceNotificationInterval = null;
        let lastServiceUnreadCount = 0;
        let serviceNotificationShown = false;
        
        // 页面加载完成后开始检测
        document.addEventListener('DOMContentLoaded', function() {
            // 检查用户角色，只有customer_service角色才启用通知
            checkServiceRoleAndStartNotification();
        });
        
        // 页面离开时停止检测
        window.addEventListener('beforeunload', function() {
            stopServiceNotification();
        });
        
        function checkServiceRoleAndStartNotification() {
            // 通过检查页面中的用户角色信息来判断是否启用通知
            const userRoleElement = document.querySelector('[data-user-role]');
            const userRole = userRoleElement ? userRoleElement.getAttribute('data-user-role') : null;
            
            // 通过URL路径判断
            const currentPath = window.location.pathname;
            const isCustomerServicePage = currentPath.startsWith('/customer-service');
            const isNotInChatPage = !currentPath.includes('/customer-service/chat/');
            
            // 只有customer_service角色且不在具体聊天页面时才启用通知
            if ((userRole === 'customer_service' || isCustomerServicePage) && isNotInChatPage) {
                console.log('启用客服全局消息通知');
                startServiceNotification();
            } else {
                console.log('当前页面不需要客服消息通知:', currentPath, 'userRole:', userRole);
            }
        }
        
        function startServiceNotification() {
            // 每5秒检查一次未读消息
            serviceNotificationInterval = setInterval(function() {
                checkServiceUnreadMessages();
            }, 5000);
            
            // 立即检查一次
            checkServiceUnreadMessages();
        }
        
        function stopServiceNotification() {
            if (serviceNotificationInterval) {
                clearInterval(serviceNotificationInterval);
                serviceNotificationInterval = null;
            }
        }
        
        function checkServiceUnreadMessages() {
            // 同时获取通知详情
            Promise.all([
                fetch('/customer-service/unread-count'),
                fetch('/customer-service/notifications')
            ])
            .then(responses => Promise.all(responses.map(r => r.json())))
            .then(([countData, notificationData]) => {
                if (countData.success) {
                    const currentUnreadCount = countData.unreadCount || 0;
                    
                    // 如果有新的未读消息且当前不在具体聊天页面
                    if (currentUnreadCount > lastServiceUnreadCount && currentUnreadCount > 0) {
                        const currentPath = window.location.pathname;
                        const isNotInChatPage = !currentPath.includes('/customer-service/chat/');
                        
                        if (isNotInChatPage && !serviceNotificationShown) {
                            console.log('检测到新的用户消息，显示客服通知');
                            
                            // 如果有通知详情，显示具体内容
                            if (notificationData.success && notificationData.notifications && notificationData.notifications.length > 0) {
                                const latestNotification = notificationData.notifications[0];
                                showServiceNotificationWithContent(currentUnreadCount, latestNotification);
                            } else {
                                showServiceNotification(currentUnreadCount);
                            }
                        } else {
                            console.log('当前在聊天页面，不显示全局通知');
                        }
                    }
                    
                    lastServiceUnreadCount = currentUnreadCount;
                    
                    // 如果没有未读消息，隐藏通知
                    if (currentUnreadCount === 0) {
                        hideServiceNotification();
                    }
                }
            })
            .catch(error => {
                console.error('检查客服未读消息失败:', error);
                // 降级到只检查数量
                fetch('/customer-service/unread-count')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const currentUnreadCount = data.unreadCount || 0;
                            if (currentUnreadCount > lastServiceUnreadCount && currentUnreadCount > 0) {
                                const currentPath = window.location.pathname;
                                const isNotInChatPage = !currentPath.includes('/customer-service/chat/');
                                if (isNotInChatPage && !serviceNotificationShown) {
                                    showServiceNotification(currentUnreadCount);
                                }
                            }
                            lastServiceUnreadCount = currentUnreadCount;
                            if (currentUnreadCount === 0) {
                                hideServiceNotification();
                            }
                        }
                    });
            });
        }
        
        function showServiceNotificationWithContent(unreadCount, notification) {
            const notificationElement = document.getElementById('customerServiceNotification');
            const title = document.getElementById('serviceNotificationTitle');
            const content = document.getElementById('serviceNotificationContent');
            
            if (notificationElement && title && content) {
                title.textContent = `${notification.senderName} 发送了新消息`;
                content.textContent = notification.messageContent || `您有 ${unreadCount} 条新的用户咨询，请及时回复`;
                
                notificationElement.style.display = 'block';
                notificationElement.classList.add('animate__animated', 'animate__slideInRight');
                
                serviceNotificationShown = true;
                
                // 播放通知音效（可选）
                playServiceNotificationSound();
                
                // 10秒后自动隐藏
                setTimeout(() => {
                    if (serviceNotificationShown) {
                        hideServiceNotification();
                    }
                }, 10000);
            }
        }
        
        function showServiceNotification(unreadCount) {
            const notification = document.getElementById('customerServiceNotification');
            const title = document.getElementById('serviceNotificationTitle');
            const content = document.getElementById('serviceNotificationContent');
            
            if (notification && title && content) {
                title.textContent = '用户发送了新消息';
                content.textContent = `您有 ${unreadCount} 条新的用户咨询，请及时回复`;
                
                notification.style.display = 'block';
                notification.classList.add('animate__animated', 'animate__slideInRight');
                
                serviceNotificationShown = true;
                
                // 播放通知音效（可选）
                playServiceNotificationSound();
                
                // 10秒后自动隐藏
                setTimeout(() => {
                    if (serviceNotificationShown) {
                        hideServiceNotification();
                    }
                }, 10000);
            }
        }
        
        function hideServiceNotification() {
            const notification = document.getElementById('customerServiceNotification');
            if (notification) {
                notification.style.display = 'none';
                notification.classList.remove('animate__animated', 'animate__slideInRight');
                serviceNotificationShown = false;
            }
        }
        
        function closeServiceNotification() {
            hideServiceNotification();
        }
        
        function goToConversations() {
            window.location.href = '/customer-service/conversations';
        }
        
        function playServiceNotificationSound() {
            // 创建简单的通知音效
            try {
                const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                const oscillator = audioContext.createOscillator();
                const gainNode = audioContext.createGain();
                
                oscillator.connect(gainNode);
                gainNode.connect(audioContext.destination);
                
                oscillator.frequency.setValueAtTime(600, audioContext.currentTime);
                oscillator.frequency.setValueAtTime(800, audioContext.currentTime + 0.1);
                
                gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
                gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
                
                oscillator.start(audioContext.currentTime);
                oscillator.stop(audioContext.currentTime + 0.3);
            } catch (error) {
                console.log('无法播放通知音效:', error);
            }
        }
        
        // 暴露全局函数供其他页面使用
        window.serviceNotification = {
            start: startServiceNotification,
            stop: stopServiceNotification,
            checkUnread: checkServiceUnreadMessages,
            show: showServiceNotification,
            hide: hideServiceNotification
        };
    </script>
    
    <!-- 添加动画效果 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
</div>
</html> 